package com.donleo.mybatis.service.impl;

import com.donleo.mybatis.common.CommonResult;
import com.donleo.mybatis.dao.IDeptMapper;
import com.donleo.mybatis.model.Dept;
import com.donleo.mybatis.service.IDeptService;
import com.donleo.mybatis.service.IRedisService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liangd
 * date 2020-12-03 11:09
 * code 部门逻辑层(使用自定义RedisTemplate设置缓存)
 */
@Service
public class DeptServiceImpl implements IDeptService {

    @Resource
    private IDeptMapper deptMapper;

    @Resource
    private IRedisService redisService;

    @Override
    public CommonResult findAll() {
        List<Dept> list;
        boolean b = redisService.hasKey("deptList:");
        if (b) {
            Object object = redisService.get("deptList:");
            list = (List<Dept>) object;
        } else {
            list = deptMapper.selectAll();
            redisService.set("deptList:",list);
        }
        return CommonResult.success(list);
    }

    @Override
    public Integer add(Dept dept) {
        dept.setId(null);
        deptMapper.insert(dept);
        return dept.getId();
    }

    @Override
    public Integer delete(Integer id) {
        redisService.del("dept:"+id);
        redisService.del("deptList:");
        return deptMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Integer update(Dept dept) {
        return deptMapper.updateByPrimaryKeySelective(dept);
    }

    @Override
    public Dept findById(Integer id) {
        //判断redis中是否存在当前key,加一个冒号生成文件夹
        boolean b = redisService.hasKey("dept:" + id);
        Dept dept;
        //如果存在，从redis中查询，否则从数据库中查询
        if (b) {
            dept = (Dept) redisService.get("dept:" + id);
        } else {
            dept = deptMapper.selectByPrimaryKey(id);
            //放入resis中
            redisService.set("dept:"+id, dept);
        }
        return dept;
    }
}
